package com.example.supermonkeysm.overall;

import com.example.supermonkeysm.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

@ControllerAdvice  // Controller全局捕获异常
@ResponseBody       // 返回前端
@Slf4j              //该注解的作用主要是操作在idea中的控制台中打印的日志信息
public class Error {
    @ExceptionHandler
    public Result<?> exceptionHandler(Exception e) {
        System.out.println("捕获到的异常为:" + e.getMessage());
        return Result.error(e.getMessage());
    }

    //    400 请求参数封装到bean时 类型转换错误
//     400 (Bad Request)
    @ExceptionHandler({MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class, MissingServletRequestParameterException.class})
    public Result<?> handleRequestParamFormatError(Exception ex) {
        log.error("handleRequestParamFormatError() bad request ex:{}", ex.getLocalizedMessage());
        return Result.error(400, ex.getLocalizedMessage());
    }

    //404 (Not Found)
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<?> handleNoHandlerFoundException(NoHandlerFoundException ex, WebRequest request) {
        log.error("handleNoHandlerFoundException() {}{}{} ", request, " exception message:", ex.getLocalizedMessage());
        return Result.error(404, ex.getLocalizedMessage());
    }


    //    405 (Method Not Allowed)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        log.error("handleHttpRequestMethodNotSupportedException() request Method Not Allowed(405) exception message:{}", ex.getLocalizedMessage());
        return Result.error(405, ex.getLocalizedMessage());
    }
}
